package org.thunms.copyright.version.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thunms.copyright.version.service.CopyrightValidateService;
import org.thunms.framework.model.Json;
/**
 * 版权管理平台
 * 版本注册子系统
 * 版本验证管理
 */
@Controller
@RequestMapping("/structure")
public class CopyrightValidateIndexController {
	
	private static final Logger logger =LoggerFactory.getLogger(CopyrightValidateIndexController.class);
	@Autowired
	private CopyrightValidateService copyrightValidateService;
	
	@RequestMapping(value="/copyright/version/copyrightValidate/web/remote/validate",method = RequestMethod.POST)
	@ResponseBody
	public void copyrightValidateAddSave(String validate,HttpServletRequest request,HttpServletResponse response,Model model) throws IOException{
		response.setContentType("text/html");
		 PrintWriter out=response.getWriter();
		 out.print(copyrightValidateService.remoteValidate(validate,getRemoteAddr(request)));
	     out.flush();
	     out.close();
	}
	
	/**
	 * 获取客户端IP地址，此方法用在proxy环境中
	 * @param req
	 * @return
	 */
	private String getRemoteAddr(HttpServletRequest req) {
		String ip = req.getHeader("X-Forwarded-For");
		if (StringUtils.isNotBlank(ip)) {
			String[] ips = StringUtils.split(ip, ',');
			if (ips != null) {
				for (String tmpip : ips) {
					if (StringUtils.isBlank(tmpip))
						continue;
					tmpip = tmpip.trim();
					if (isIPAddr(tmpip) && !tmpip.startsWith("10.") && !tmpip.startsWith("192.168.")
							&& !"127.0.0.1".equals(tmpip)) {
						return tmpip.trim();
					}
				}
			}
		}
		ip = req.getHeader("x-real-ip");
		if (isIPAddr(ip))
			return ip;
		ip = req.getRemoteAddr();
		if (isIPAddr(ip))
			return ip;
		return "127.0.0.1";
	}

	/**
	 * 判断字符串是否是一个IP地址
	 * @param addr
	 * @return
	 */
	private boolean isIPAddr(String addr) {
		if (StringUtils.isEmpty(addr))
			return false;
		String[] ips = StringUtils.split(addr, '.');
		if (ips.length != 4)
			return false;
		try {
			int ipa = Integer.parseInt(ips[0]);
			int ipb = Integer.parseInt(ips[1]);
			int ipc = Integer.parseInt(ips[2]);
			int ipd = Integer.parseInt(ips[3]);
			return ipa >= 0 && ipa <= 255 && ipb >= 0 && ipb <= 255 && ipc >= 0 && ipc <= 255 && ipd >= 0 && ipd <= 255;
		} catch (Exception e) {
		}
		return false;
	}

}
